import type { TreeNodeType, TreeDataType, TreeRawDataType } from "../type";
import { isUndefined } from "@ct0/functions";

export const NEW_KEY_PREFIX = "_new_add_";
export const ROOT_NODE = "_root_node_";

export function isNew(key: string | number) {
  return String(key).startsWith?.(NEW_KEY_PREFIX) ?? false;
}

export function isRoot(key: string | number) {
  return key == ROOT_NODE;
}

export function createNewTempNode() {
  return {
    key: NEW_KEY_PREFIX + (new Date().getTime() + Math.random()),
    title: "新节点",
  };
}

export function replaceTempNodeKey(key: string | number) {
  return typeof key == "string" ? key.replace(NEW_KEY_PREFIX, "_putted_") : key;
}

export function copyRawTreeData(
  treeData?: TreeDataType,
  transfer?: (node: { key: string | number; title: string }) => {
    key: string | number;
    title: string;
  }
): TreeRawDataType | undefined {
  if (!treeData) return;
  const data: TreeRawDataType = [];
  for (const i of treeData) {
    let node = { key: i.key, title: i.title };
    if (transfer) node = transfer(node);
    data.push({
      ...node,
      children: copyRawTreeData(i.children),
    });
  }
  return data;
}

export function flatten({
  level = 1,
  treeData,
  verticalLines,
  parentKey,
  editable,
  maxShowDeepth,
  maxCreateDeepth,
}: {
  level?: number;
  treeData: TreeDataType;
  verticalLines: Array<boolean>;
  parentKey: string | number;
  editable?: boolean;
  maxShowDeepth?: number;
  maxCreateDeepth?: number;
}) {
  const nodes: Array<TreeNodeType> = [];
  for (let i = 0; i < treeData.length; i++) {
    const {
      key,
      title,
      children,
      disableRemove,
      disableAddChild,
      disableEdit,
      count,
      disableCheck,
      disableClick,
    } = treeData[i];
    // let currentKeys = [...keys, key];
    const isLast = i == treeData.length - 1;
    /**
     * 禁止添加子节点情况
     * 1、主动禁止，添加 disableAddChild = true
     * 2、被动禁止，当设置了 maxDeepth?.create 时，超过深度则不能新增子节点
     */
    const noAdd =
      disableAddChild ||
      (isUndefined(maxCreateDeepth) ? false : maxCreateDeepth <= level);

    const isLeaf = !children?.[0];

    nodes.push({
      key,
      count,
      parentKey,
      title,
      verticalLines,
      isLeaf,
      isLast,
      disableAddChild: noAdd,
      disableRemove,
      disableEdit,
      disableCheck,
      disableClick,
    });

    /** 设置 maxDeepth?.show时，超过深度不显示子节点 */
    if (!isLeaf && (!maxShowDeepth || maxShowDeepth > level)) {
      nodes.push(
        ...flatten({
          level: level + 1,
          parentKey: key,
          treeData: children,
          verticalLines: [...verticalLines, !isLast],
          editable,
          maxShowDeepth,
          maxCreateDeepth,
        })
      );
    }
  }
  return nodes;
}

export function getAllChildrenKeys(
  key: string | number,
  treeData: TreeDataType
): Array<string | number> {
  const keys: Array<string | number> = [];

  const pushAllKeys = (data?: TreeDataType) => {
    if (!data) return;
    for (const i of data) {
      keys.push(i.key);
      pushAllKeys(i.children);
    }
  };

  const getNode: (data?: TreeDataType) => TreeDataType[0] | undefined = (
    data
  ) => {
    if (!data) return;
    for (const i of data) {
      if (i.key == key) return i;
      const n = getNode(i.children);
      if (n) return n;
    }
  };

  const node = getNode(treeData);

  if (node) {
    keys.push(node.key);
    pushAllKeys(node.children);
  }

  return keys;
}
